<template>
  <BasicModal v-bind="$attrs" @ok="handleOk" @register="registerModal">
    <BasicForm @register="registerForm">
      <template #parentId="{ model, field }">
        <Select showSearch optionFilterProp="label" v-model:value="model[field]">
          <SelectOption v-for="item in selectOptions" :value="item.id" :label="item['cnName']">
            <span>{{ item['cnName'] }}</span>
            <span style="color: rgb(128, 128, 128)" v-if="item['parentCnName']">
              - [ {{ item['parentCnName'] }} ]</span
            >
          </SelectOption>
        </Select>
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script setup lang="ts">
  import { ref, unref } from 'vue';
  import { modalFormSchema } from './data';
  import mcApi from 'mc-c2b2m-operator-api';
  import { useMessage } from '@/hooks/web/useMessage';
  import { Select, SelectOption } from 'ant-design-vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { BasicModal, useModalInner } from '@/components/Modal';

  const { SpuModule } = mcApi;
  const { BizMetaArrApi } = SpuModule;

  const props = defineProps({
    treeFlatData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  });

  const [registerForm, { setFieldsValue, resetFields, validate, getFieldsValue }] = useForm({
    labelWidth: 100,
    schemas: modalFormSchema,
    baseColProps: { span: 22 },
    showActionButtonGroup: false,
  });

  const selectOptions = ref<Recordable[]>([]);
  const handleSelectOptions = () => {
    BizMetaArrApi.getBizMetaAttrPage().then((res: any) => {
      selectOptions.value = res?.items || [];
      // 编辑时，如果节点父级信息没在options内，则手动push进去
      if (ifUpdate.value) {
        const { parentId, parentCnName } = getFieldsValue();
        const find = selectOptions.value.find((find) => find.id === parentId);
        if (!!find) return;
        // 找到父级的父级，协助label展示
        const pFind = props.treeFlatData.find((find: Recordable) => find.id === parentId);
        selectOptions.value.push({
          id: parentId,
          cnName: parentCnName,
          parentCnName: pFind.parentCnName,
        });
      }
    });
  };

  const ifUpdate = ref<boolean>(false);
  const [registerModal, { setModalProps }] = useModalInner(async (data) => {
    await resetFields();
    ifUpdate.value = !!data.ifUpdate;
    setModalProps({
      minHeight: 50,
      confirmLoading: false,
      title: `${ifUpdate.value ? '编辑' : '新增'}业务元属性`,
    });
    handleSelectOptions();
    const { record, parentId } = data;
    if (unref(ifUpdate)) {
      const { uiComponentCodeList } = record;
      !uiComponentCodeList?.length && (record.uiComponentCodeList = []);
      await setFieldsValue(data.record);
    } else {
      parentId && (await setFieldsValue({ parentId }));
    }
  });

  const { createMessage } = useMessage();
  const emits = defineEmits(['success']);
  async function handleOk() {
    try {
      const values: any = await validate();
      setModalProps({ confirmLoading: true });
      const fun = unref(ifUpdate)
        ? BizMetaArrApi.updateBizMetaAttr
        : BizMetaArrApi.createBizMetaAttr;
      await fun(values);
      createMessage.success(`${unref(ifUpdate) ? '编辑' : '新增'}成功！`);
      emits('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style scoped lang="less"></style>
